package com.mycompany.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mycompany.dao.BookingDao;
import com.mycompany.dto.EventBookingStatusDto;
import com.mycompany.model.Booking;
import com.mycompany.model.Event;
import com.mycompany.model.User;
import com.mycompany.service.BookingManager;
import com.mycompany.service.EventManager;
import com.mycompany.service.UserManager;

@Service("bookingManager")
public class BookingManagerImpl extends GenericManagerImpl<User, Long> implements BookingManager {

	private UserManager 	userManager;
	private EventManager 	eventManager;
	private BookingDao		bookingDao;
	
	
	@Resource
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	@Resource
	public void setEventManager(EventManager eventManager) {
		this.eventManager = eventManager;
	}

	@Resource
	public void setBookingDao(BookingDao bookingDao) {
		this.bookingDao = bookingDao;
	}

	public void saveBooking(Booking booking) {
		// TODO Auto-generated method stub

	}

	public void updateBookings(String userName,
			List<EventBookingStatusDto> eventBookingStatusList) {
		
		User user = userManager.getUserByUsername(userName);
		
		for (EventBookingStatusDto eventBookingStatus : eventBookingStatusList) {
			Event event = eventManager.getEvent(eventBookingStatus.getEventId());
			if (event != null) {
				Booking booking = bookingDao.getBooking(user.getId(), eventBookingStatus.getEventId());
				if (booking == null) {
					if (eventBookingStatus.isBooked()) {						
						booking = new Booking(user, event);
						booking = bookingDao.saveBooking(booking);
					}
				} else {
					if (!eventBookingStatus.isBooked()) {
						user.getBookings().remove(booking);
						event.getBookings().remove(booking);							
						bookingDao.deleteBooking(booking);
					}
				}
			}			
		}
		
	}

	public List<EventBookingStatusDto> getBookingsForUser(String userName) {			
		List<Event> events = eventManager.getEventList();				
		
		User user = userManager.getUserByUsername(userName);
		List<EventBookingStatusDto> eventBookingStatusList = new ArrayList<EventBookingStatusDto>();	
		
		EventBookingStatusDto eventBookingStatus;

		for (Event event : events) {
			eventBookingStatus = new EventBookingStatusDto(event.getId(), event.getName(), false);
			if (user.getBookings().size()>0) {
				for (Booking booking : user.getBookings()) {						
					if (event.getId().equals(booking.getEvent().getId())) {
						eventBookingStatus.setBooked(true);
					}
					
				}
			}
			eventBookingStatusList.add(eventBookingStatus);
		}					
		
		return eventBookingStatusList;
		
	}

		
	
}
